package com.mall.b2c.service.impl;

import static com.mall.b2c.Constants.MAX_RECEIVER_NUM;

import java.util.List;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.mall.b2c.bean.ReceiverBean;
import com.mall.b2c.dao.ReceiverDao;
import com.mall.b2c.domain.member.MemberDomain;
import com.mall.b2c.domain.member.ReceiverDomain;
import com.mall.b2c.service.MemberService;
import com.mall.b2c.service.ReceiverService;
import com.mall.common.domain.AreaDomain;
import com.mall.common.exception.NoticeException;
import com.mall.common.hibernate.Finder;
import com.mall.common.service.AreaService;
import com.mall.common.service.impl.BaseServiceImpl;

/**
 * Service实现类 - 会员
 */
@Service
@Transactional(readOnly=true)
public class ReceiverServiceImpl extends BaseServiceImpl<ReceiverDomain, Long> implements ReceiverService{
	@Resource private MemberService memberService;
	@Resource private AreaService areaService;
	
	@Resource
	public void setBaseDao(ReceiverDao receiverDao){
		super.setBaseDao(receiverDao);
	}

	@Override
	public List<ReceiverBean> getRecerverList(Long memberId) {
		Finder finder = Finder.create("select new com.mall.b2c.bean.ReceiverBean(bean) from ReceiverDomain bean where bean.member.id = :memberId order by bean.isDefault desc");
		finder.setParam("memberId", memberId);
		return finder.findHQLList();
	}
	
	/**
	 * 保存收货地址
	 * @param receiver
	 * @return void
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public ReceiverBean saveReceiver(ReceiverBean receiver, Long memberId){
		MemberDomain member = memberService.find(memberId);
		if(member == null){
			throw new NoticeException("会员不存在");
		}
		if(member.getReceiverSet().size() >= MAX_RECEIVER_NUM){
			throw new NoticeException("member.max.receiver", new Object[]{MAX_RECEIVER_NUM});
		}
		if(StringUtils.isBlank(receiver.getName())){
			throw new NoticeException("收货人不能为空");
		}
		if(StringUtils.isBlank(receiver.getAddress())){
			throw new NoticeException("详细地址不能为空");
		}
		if(StringUtils.isBlank(receiver.getContact())){
			throw new NoticeException("联系方式不能为空");
		}
		if(StringUtils.isBlank(receiver.getAreaTree())){
			throw new NoticeException("地区不能为空");
		}
		String[] areaIds = receiver.getAreaTree().split(",");
		if(!Pattern.matches("^\\d+$", areaIds[areaIds.length - 1])){
			throw new NoticeException("地区不存在");
		}

		Long areaId =Long.valueOf(areaIds[areaIds.length - 1]);

		AreaDomain area = areaService.find(areaId);
		if(area == null){
			throw new NoticeException("地区不存在");
		}
		if(receiver.getIsDefault() != null && receiver.getIsDefault()){
			List<ReceiverDomain> list = getOtherReceiver(null, memberId);
			for(ReceiverDomain r : list){
				r.setIsDefault(false);
				update(r);
			}
		}
		ReceiverDomain bean = new ReceiverDomain();
		bean.setAddress(receiver.getAddress());
		bean.setArea(area);
		bean.setContact(receiver.getContact());
		bean.setIsDefault(receiver.getIsDefault());
		bean.setMember(member);
		bean.setName(receiver.getName());
		bean.setZipCode(receiver.getZipCode());
		bean.setAlias(receiver.getAlias());
		persist(bean);
		receiver.setId(bean.getId());
		receiver.setArea(area.getFull_name());
		receiver.setId(receiver.getId());
		return receiver;
	}
	
	private List<ReceiverDomain> getOtherReceiver(Long ignoreId, Long memberId){
		Finder finder = Finder.create("from ReceiverDomain bean where bean.member.id = :memberId");
		finder.setParam("memberId", memberId);
		if(ignoreId != null){
			finder.append(" and bean.id != :ignoreId");
			finder.setParam("ignoreId", ignoreId);
		}
		return finder.findHQLList();
	}
	
	/**
	 * 更新收货地址
	 * @param receiver
	 * @return void
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void updateReceiver(ReceiverBean receiver, Long memberId){
		if(StringUtils.isBlank(receiver.getName())){
			throw new NoticeException("收货人不能为空");
		}
		if(StringUtils.isBlank(receiver.getAddress())){
			throw new NoticeException("详细地址不能为空");
		}
		if(StringUtils.isBlank(receiver.getContact())){
			throw new NoticeException("联系方式不能为空");
		}
		if(StringUtils.isBlank(receiver.getAreaTree())){
			throw new NoticeException("地区不能为空");
		}
		String[] areaIds = receiver.getAreaTree().split(",");
		if(!Pattern.matches("^\\d+$", areaIds[areaIds.length - 1])){
			throw new NoticeException("地区不存在");
		}
		ReceiverDomain bean = getReceiver(receiver.getId(), memberId);
		if(bean == null){
			throw new NoticeException("收货地址不存在");
		}
		AreaDomain area = areaService.find(Long.valueOf(areaIds[areaIds.length - 1]));
		if(area == null){
			throw new NoticeException("地区不存在");
		}
		bean.setArea(area);
		if(receiver.getIsDefault() != null && receiver.getIsDefault()){
			List<ReceiverDomain> list = getOtherReceiver(receiver.getId(), memberId);
			for(ReceiverDomain r : list){
				r.setIsDefault(false);
				update(r);
			}
		}
		bean.setAddress(receiver.getAddress());
		bean.setContact(receiver.getContact());
		if(receiver.getIsDefault() != null){
			bean.setIsDefault(receiver.getIsDefault());
		}
		bean.setName(receiver.getName());
		bean.setZipCode(receiver.getZipCode());
		bean.setAlias(receiver.getAlias());
		update(bean);
	}

	@Override
	public ReceiverDomain getReceiver(Long receiverId, Long memberId) {
		Finder finder = Finder.create("from ReceiverDomain bean where bean.id = :receiverId and bean.member.id = :memberId");
		finder.setParam("receiverId", receiverId);
		finder.setParam("memberId", memberId);
		Object obj = finder.findUniqueByHQL();
		if(obj != null){
			return (ReceiverDomain) obj; 
		}
		return null;
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void deleteReceiver(Long receiverId, Long memberId) {
		ReceiverDomain bean = getReceiver(receiverId, memberId);
		if(bean == null){
			throw new NoticeException("收货地址不存在");
		}
		remove(bean);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public Boolean setDefault(Long memberId, Long receiverId) {
		String hql = "update ReceiverDomain bean set bean.isDefault = true where bean.member.id = :memberId and bean.id = :receiverId";
		int result = getEntityManager().createQuery(hql).setParameter("memberId", memberId).setParameter("receiverId", receiverId).executeUpdate();
		if(result > 0) {
			hql = "update ReceiverDomain bean set bean.isDefault = false where bean.member.id = :memberId and bean.id != :receiverId";
			getEntityManager().createQuery(hql).setParameter("memberId", memberId).setParameter("receiverId", receiverId).executeUpdate();
		}
		return result > 0;
	}
	
}
